<?php
/**
 * Created by PhpStorm.
 * User: Progress
 * Date: 2019/10/28
 * Time: 17:19
 */
namespace app\api\controller;

use app\admin\model\MiningCoin;
use app\admin\model\MiningRecharge;
use app\admin\model\MiningUserWallet;
use app\admin\model\MiningWithdraw;
use app\admin\model\UserMiner;
use app\admin\model\WaterMining;
use app\common\controller\Api;
use app\common\model\Config;
use think\Validate;

/**
 * 系统文章
 */
class Mining extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function pledge()
    {
        $id = $this->request->post('id');
        $data = UserMiner::where('id',$id)->where('user_id',$this->auth->getUser()->id)->find();
        if ($data->pledge_status == 1) {
            UserMiner::where('id',$id)->where('user_id',$this->auth->getUser()->id)->update(['pledge_status' => 0]);
            $this->success('停止质押成功！');
        } else {
            UserMiner::where('id',$id)->where('user_id',$this->auth->getUser()->id)->update(['pledge_status' => 1]);
            $this->success('开启质押成功！');
        }
    }

    /**
     * 余额
     */
    public function balance()
    {
        $mining_coin = MiningCoin::select();
        $data = [];
        foreach ($mining_coin as $value)
        {
            $tmp['name'] = $value->coin_type;
            $tmp['balance'] = MiningUserWallet::where('user_id',$this->auth->getUser()->id)
                ->where('mining_coin_id',$value->id)->value('balance') ?? 0;
            $data['data'][] = $tmp;
            $data['balance'][$value->coin_type] = $tmp['balance'];
        }

        $this->success('ok',$data);
    }

    /**
     * 余额详情
     */
    public function balanceDetail()
    {
        $this->loadadminlang('mining/water_mining');

        $page = $this->request->get('page') ?? 1;
        $coin_type = strtoupper($this->request->get('coin_type'));
        if (empty($coin_type)) {
            $this->error(__('unknown data format'));
        }
        $coin_type_id = MiningCoin::where('coin_type',$coin_type)->value('id');

        $data['data'] = WaterMining::field('detail_id,money,balance,mark,type,create_time')
            ->where('user_id',$this->auth->getUser()->id)
            ->where('coin_type',$coin_type)->page($page,50)
            ->order('id','desc')
            ->select();
//        foreach ($data['data'] as $value) {
//            if ($value->type == MINING_WATER_TRANSFER_IN || $value->type == MINING_WATER_TRANSFER_OUT) {
//                $value->type =  $value->type_text . '-'. $value->mark;
//            }
//        }
        $data['balance'] = MiningUserWallet::where('mining_coin_id',$coin_type_id)
                ->where('user_id',$this->auth->getUser()->id)->value('balance') ?? 0;
//        $data['profit'] = 123;  //TODO
//        $data['withdraw'] = 123;  //TODO
//        $data['pledge'] = 123;  //TODO
//        $data['lock'] = 123;  //TODO
        $this->success('ok',$data);
    }

    public function balanceDetails()
    {
        $this->loadadminlang('mining/water_mining');

        $page = $this->request->get('page') ?? 1;
        $type = $this->request->get('type') ?? 'recharge';
        $coin_type = strtoupper($this->request->get('coin_type'));
        if (empty($coin_type)) {
            $this->error(__('unknown data format'));
        }
        $coin_type_id = MiningCoin::where('coin_type',$coin_type)->value('id');

        if ($type == "recharge") {
            $type = [MINING_WATER_RECHARGE];
        } else {
            $type = [MINING_WATER_WITHDRAW_APPEAL,MINING_WATER_WITHDRAW_SUCCESS];
        }
        $data['data'] = WaterMining::field('detail_id,money,balance,mark,type,create_time')
            ->where('user_id',$this->auth->getUser()->id)
            ->whereIn('type',$type)
            ->where('coin_type',$coin_type)->page($page,50)
            ->order('id','desc')
            ->select();

        $this->success('ok',$data);
    }

    /**
     * 充币
     */
    public function onRecharge()
    {
        $data['address'] = MiningUserWallet::where('user_id',$this->auth->getUser()->id)->where('mining_coin_id',2)->value('address');
        if (empty($data['address'])) {
            $result = file_get_contents('http://8.210.80.109:10001/wallet/getaddr/ETHEREUM/1');
            $result = json_decode($result,true);
            if ($result['code'] == 1) {
                $data['address'] = $result['data'][0];
                MiningUserWallet::where('user_id',$this->auth->getUser()->id)
                    ->where('mining_coin_id',2)->update(['address' => $data['address']]);
            }
        }
        $this->success('ok',$data);
    }

    //充值
    public function recharge()
    {
//        $address = "XXXXXXXXXXXXXXXXXXXXXXXXX";     //TODO
        if (empty($this->request->post())) {
            $coin_type = $this->request->get('coin_type');
//            $mining_coin = MiningCoin::where('coin_type',$coin_type)->find();
//            $data['recharge_lowest'] = $mining_coin->recharge_lowest;
            if ($coin_type == COIN1) {
                $address = Config::where('name','usdt_address')->value('value');
            } else {
                $address = Config::where('name','fil_address')->value('value');
            }
            $data['address'] = $address;
            $this->success('ok',$data);
        }

        $number = $this->request->post('number');
        $hash = $this->request->post('hash');
        $images = $this->request->post('image');
        $mining_coin_id = $this->request->post('coin_id');
        if ($mining_coin_id == COIN1_ID) {
            $address = Config::where('name','usdt_address')->value('value');
        } else {
            $address = Config::where('name','fil_address')->value('value');
        }
        $mining_coin = MiningCoin::where('id',$mining_coin_id)->find();
        if (empty($mining_coin)) {
            $this->error('找不到该币种');
        }
        if ($mining_coin->recharge_lowest > $number) {
            $this->error('充值最低金额为：'.$mining_coin->recharge_lowest);
        }
        $row = MiningRecharge::create([
            'user_id' => $this->auth->getUser()->id,
            'mining_coin_id' => $mining_coin_id,
            'mining_coin_str' => $mining_coin->coin_type,
            'money' => $number,
            'address' => $address,
            'hash'=> $hash,
            'images' => $images
        ]);

         WaterMining::create([
             'detail_id' => $row->id,
             'user_id' => $this->auth->getUser()->id,
             'type' => MINING_WATER_RECHARGING,
             'coin_type' => $mining_coin->coin_type,
             'money' => $number,
         ]);

        $this->success('提交成功');
    }

    /**
     * 提币
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function withdraw()
    {
        $user_id = $this->auth->getUser()->id;
        if (empty($this->request->post())) {
            $coin_type = $this->request->get('coin_type');
            $mining_type = MiningCoin::where('coin_type',$coin_type)->find();
            $data['withdraw_handling_fee'] = $mining_type->withdraw_handling_fee;
            $data['withdraw_lowest'] = $mining_type->withdraw_lowest;
            $data['balance'] = MiningUserWallet::where('mining_coin_id',$mining_type->id)
                    ->where('user_id',$user_id)->value('balance') ?? 0;

            $this->success('ok',$data);
        }

        $validate = \think\Validate::make([
            'amount|数量' => 'require|number',
            'address|地址' => 'require',
            'coin_type|币种' => 'require',
        ]);
        if (!$validate->check($this->request->post()))
            $this->error($validate->getError());

        $amount = $this->request->post('amount');
        $address = $this->request->post('address');
        $coin_type = $this->request->post('coin_type');
        $coin_type_data = MiningCoin::where('coin_type',$coin_type)->find();
        if (empty($coin_type_data)) {
            $this->error(__('unknown data format'));
        }

        if (empty($coin_type_data->withdraw_status)) {
            $this->error(__('Withdraw coin is closing'));
        }
        if ($this->auth->getUser()->deal_password != $this->request->post('deal_password')) {
            $this->error(__('Transaction password is incorrect'));
        }
        //验证码
//            $captcha = trim($this->request->post('captcha'));
//                $captcha_check = \app\common\library\Sms::check($this->auth->getUser()->mobile, $captcha, 'withdraw');
//            if (!$captcha_check) {
//                $this->error('验证码不正确!');
//            }

        $withdraw_lowest = $coin_type_data->withdraw_lowest;
        if ($amount < $withdraw_lowest) {
            $this->error(__('Amount cannot be less than').' '.$withdraw_lowest);
        }

        $handling_fee = $coin_type_data->withdraw_handling_fee;
//        $handling_fee = round($handling_fee * $amount / 100, 6);

        $balance = MiningUserWallet::where('user_id',$user_id)
                ->where('mining_coin_id',$coin_type_data->id)->value('balance') ?? 0;

        if ($balance < $amount) {
            $this->error($coin_type.__('Balance not enough'));
        }

        MiningUserWallet::where('user_id',$user_id)
            ->where('mining_coin_id',$coin_type_data->id)->setDec('balance',$amount);



        $withdraw_data = MiningWithdraw::create([
            'user_id' => $user_id,
            'number' => $amount,
            'hand_fee' => $handling_fee,
            'amount' => $amount - $handling_fee,
            'address' => $address,
            'mining_coin_id' => $coin_type_data->id,
            'mining_coin_str' => $coin_type_data->coin_type,
        ]);

        WaterMining::create([
            'detail_id' =>$withdraw_data->id,
            'user_id' => $user_id,
            'type' => MINING_WATER_WITHDRAW_APPEAL,
            'coin_type' => $coin_type,
            'money' => '-'.$amount,
            'balance' => $balance - $amount,
        ]);
        $this->success(__('Appeal successful'));
    }

    /**
     * 转账
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function transfer()
    {
        $user_id = $this->auth->getUser()->id;

        if (empty($this->request->post()))
        {
            $coin_type = $this->request->get('coin_type');
            $coin_type_data = MiningCoin::where('coin_type', $coin_type)->find();
            $data['balance'] = MiningUserWallet::where('user_id',$user_id)
                ->where('mining_coin_id',$coin_type_data->id)->value('balance') ?? 0;
            $data['transfer_lowest'] = $coin_type_data->transfer_lowest;
            $data['transfer_handling_fee'] = $coin_type_data->transfer_handling_fee;
            $this->success('ok',$data);
        }

        $account = $this->request->post('account');
        $money = $this->request->post('number');
        $coin_type = $this->request->post('coin_type');

        $coin_type_data = MiningCoin::where('coin_type', $coin_type)->find();
        if (empty($coin_type_data)) {
            $this->error(__('unknown data format'));
        }
        if (empty($coin_type_data->transfer_status)) {
            $this->error(__('Transfer coin is closing'));
        }
        if (Validate::regex($account, "^1\d{10}$")) {
            $to_user = \app\common\model\User::field('money,id,mobile')->where('mobile', $account)->find();
        } else {
            $to_user = \app\common\model\User::field('money,id,email')->where('email', $account)->find();
        }
        if (empty($to_user)) {
            $this->error(__('Transfer user not exist'));
        }

        if ($this->auth->getUser()->deal_password != $this->request->post('deal_password')) {
            $this->error(__('Transaction password is incorrect'));
        }
//        $captcha = $this->request->post('code');     //验证码
//        $ret = \app\common\library\Sms::check($this->auth->getUser()->mobile, $captcha, 'transfer');
//        if (!$ret) {
//            $this->error('转账验证码不正确');
//        }
        if ($money < $coin_type_data->transfer_lowest) {
            $this->error(__('Amount cannot be less than').' '.$coin_type_data->transfer_lowest);
        }

        $balance = MiningUserWallet::where('user_id',$user_id)->where('mining_coin_id',$coin_type_data->id)->value('balance') ?? 0;
        if ($balance < $money) {
            $this->error(__('Balance not enough'));
        }

        //手续费
        $handling_fee = $coin_type_data->transfer_handling_fee;
//        $handling_fee = round($handling_fee * $money / 100,6);
        $increase_money = $money - $handling_fee;

        MiningUserWallet::where('user_id',$user_id)->where('mining_coin_id',$coin_type_data->id)->setDec('balance', $money);
        MiningUserWallet::where('user_id',$to_user->id)->where('mining_coin_id',$coin_type_data->id)->setInc('balance', $increase_money);
        WaterMining::create([
            'relate_user_id' => $to_user->id,
            'user_id' => $user_id,
            'type' => MINING_WATER_TRANSFER_OUT,
            'money' => '-'.$money,
            'coin_type' => $coin_type,
            'mark' => $account
        ]);

        WaterMining::create([
            'relate_user_id' => $user_id,
            'user_id' => $to_user->id,
            'type' => MINING_WATER_TRANSFER_IN,
            'money' => $increase_money,
            'coin_type' => $coin_type,
            'mark' => $this->auth->getUser()->mobile ?? $this->auth->getUser()->email
        ]);

        $this->success(__('Transfer successful'));
    }


}